package com.sgj.gulimall.ssoclient.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/10 9:41
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登陆即可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 获取所有员工
     * @param token 非必填，用于感知用户是否登陆
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/boss")
    public String employees(@RequestParam(value = "token", required = false) String token, Model model, HttpSession session) {

        if (StringUtils.isNotBlank(token)) {
            // 用户登陆成功，存入session
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
            session.setAttribute("loginUser", forEntity.getBody());
        }

        Object loginUser = session.getAttribute("loginUser");
        if (Objects.isNull(loginUser)) {
            // 未登录，跳转到登陆页面进行登陆
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        }

        List<String> emps = new ArrayList<>();
        emps.add("张三");
        emps.add("李四");

        model.addAttribute("emps", emps);
        return "list";
    }
}